<template>
  <div class="users-container">
<!--    面包屑导航-->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
<!--    卡片区域-->
    <el-card class="box-card">
<!--      搜索框-->
      <div class="searchBox">
        <el-input placeholder="请输入内容"
                  v-model="paramsInfo.query"
                  clearable
                  @clear="initUserList"
                  style="width: 50%;margin-right: 20px">
          <el-button slot="append" icon="el-icon-search" @click="initUserList"></el-button>
        </el-input>
        <el-button type="primary"  @click="dialogVisible = true">添加用户</el-button>
      </div>
<!--      表格数据渲染-->
      <el-table
          :data="userInfo"
          border
          style="width: 100%">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username"  label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
<!--            通过element-ui插槽获取一整行的数据-->
<!--            {{scope.row.mg_state}}-->

            <el-switch
                v-model="scope.row.mg_state"
                @change="changeState(scope.row)"
                active-color="#13ce66"
                inactive-color="#dcdfe6">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">

              <el-button type="primary" icon="el-icon-edit" size="mini" @click="editForm(scope.row.id)"></el-button>
            <el-tooltip  effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-star-off" size="mini" @click="setRoles(scope.row)"></el-button>
            </el-tooltip>

              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteForm(scope.row.id)"></el-button>

          </template>
        </el-table-column>



      </el-table>
<!--      分页-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="paramsInfo.pagenum"
          :page-sizes="[1, 3, 5, 10]"
          :page-size="paramsInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>
<!--    添加用户dialog对话框-->
    <el-dialog
        title="添加用户信息"
        :visible.sync="dialogVisible"
        width="50%"
        @close="resetAddForm"
        >
      <span>
        <el-form ref="addForm" :model="userForm" :rules="userRules" label-width="80px">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="userForm.username"></el-input>
            </el-form-item>
          <el-form-item label="密码" type="password" prop="password">
                <el-input v-model="userForm.password"></el-input>
            </el-form-item>
          <el-form-item label="邮箱" type="email" prop="email">
                <el-input v-model="userForm.email"></el-input>
            </el-form-item>
          <el-form-item label="手机" prop="mobile">
                <el-input v-model="userForm.mobile"></el-input>
            </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible=false">取 消</el-button>
    <el-button type="primary" @click="saveAddForm">确 定</el-button>
  </span>
    </el-dialog>


    <!--    修改用户信息dialog对话框-->
    <el-dialog
        title="修改用户信息"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="resetEditForm"
    >
      <span>
        <el-form ref="editForm" :model="editUserInfo" :rules="userRules" label-width="80px">
            <el-form-item label="用户名">
                <el-input disabled v-model="editUserInfo.username"></el-input>
            </el-form-item>

          <el-form-item label="邮箱" type="email" prop="email">
                <el-input v-model="editUserInfo.email"></el-input>
            </el-form-item>
          <el-form-item label="手机" prop="mobile">
                <el-input v-model="editUserInfo.mobile"></el-input>
            </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible=false">取 消</el-button>
    <el-button type="primary" @click="saveEditForm">确 定</el-button>
  </span>
    </el-dialog>

    <!--    分配用户角色dialog对话框-->
    <el-dialog
        title="分配角色"
        :visible.sync="setRolesDialogVisible"
        width="50%"
        >
      <div>
        <p>当前用户：{{rolesList.username}}</p>
        <p>当前角色：{{rolesList.role_name}}</p>
        <el-select v-model="selectedId" placeholder="请选择">
          <el-option
              v-for="item in getRolesInfo"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRolesDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="sureSetRoles">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  deleteUserInfo,
  getAddUserInfo,
  getIDUserInfo,
  getUserList,
  getUserStatus,
  putIDUserInfo, rolesManage, submitRolesManage
} from "@/utils/loginAPI";

export default {
  name: "User",
  data(){
    return{
      //用户列表的查询参数
      paramsInfo:{
        query:'',
        pagenum:1,
        //当前每页显示多少条数据
        pagesize:3,

      },
      userInfo: [],
      total:0,
      value:true,
      //添加用户信息
      dialogVisible:false,
      //修改用户信息
      editDialogVisible:false,
      //删除

      //用户信息添加
      userForm:{
        username:'',
        password:'',
        email:'',
        mobile:'',
      },
      //用户信息修改
      editUserInfo:{},
      //表单规则
      userRules:{
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 5, max: 11, message: '长度在 5 到 10 个字符', trigger: 'blur' }
        ],

      },
      //分配用户角色
      setRolesDialogVisible:false,
      rolesList:{},
      getRolesInfo:[],
      //已选中的id值
      selectedId:'',
    }
  },
  created() {
    this.initUserList();
  },
  methods:{
    async initUserList(){
      const {data:user}=await getUserList(this.paramsInfo);
      // console.log(user);
      if(user.meta.status!==200) return this.$message.error(user.meta.msg);
      this.userInfo=user.data.users;
      this.total=user.data.total;
    },
    //分页
    //监听pageSize改变
    handleSizeChange(newSize) {
      console.log(newSize);
      this.paramsInfo.pagesize=newSize;
      //重新渲染列表数据
      this.initUserList();
    },
    //监听页码值的改变
    handleCurrentChange(newPage) {
      this.paramsInfo.pagenum=newPage;
      //重新渲染列表数据
      this.initUserList();
    },
    //监听状态的变化  通过put请求发送给数据库 并保存
    async changeState(info){
      // console.log(info);
      const {data:res}=await getUserStatus(info.id,info.mg_state);
      if(res.meta.status!==200) {
        //把状态重置回去
        info.mg_state= !info.mg_state;
        return this.$message.error(res.meta.msg);

      }else{
        console.log("成功了",res);
      }

    },
    resetAddForm(){
      this.$refs.addForm.resetFields();
    },
    saveAddForm(){
      this.$refs.addForm.validate(async val=>{
        if(!val) return this.$message.error('表单验证未通过');
        const {data:res}=await getAddUserInfo(this.userForm);
        // console.log(res);
        if(res.meta.status!==201) return this.$message.error(res.meta.msg);
        this.dialogVisible=false;
        await this.initUserList();

      })

    },
    //编辑
     async editForm(id){
      console.log(id);
      //根据id查询用户信息
      const {data:res}=await getIDUserInfo(id);
      if(res.meta.status!==200) return this.$message.error(res.meta.msg);
      //把数据渲染到编辑框中
      this.editUserInfo=res.data;
      // console.log(res);
      this.editDialogVisible=true;
    },
    resetEditForm(){
      this.$refs.editForm.resetFields();
    },
     saveEditForm(){
      this.$refs.editForm.validate(async val=>{
        if(!val) return this.$message.error('表单验证未通过');
        const {data:res}=await putIDUserInfo(this.editUserInfo.id,this.editUserInfo);
        if(res.meta.status!==200) return this.$message.error(res.meta.msg);
        console.log(res);
        this.editDialogVisible=false;
        await this.initUserList();
        this.$message.success(res.meta.msg);
      })
    },
    //删除
    deleteForm(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
        const {data:res}=await deleteUserInfo(id);
        await this.initUserList();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //分配用户角色
    async setRoles(roles){
      this.setRolesDialogVisible=true;
      this.rolesList=roles;
      //获取角色列表
      const {data:res}=await rolesManage();
      this.getRolesInfo=res.data;
    },
    async sureSetRoles(selectedId){
      if(!this.selectedId) return this.$message.error('请选择角色！！');
      const {data:res}=await submitRolesManage(this.rolesList.id,{rid:this.selectedId});
      if(res.meta.status!==200) return this.$message.error(res.meta.msg);
      this.$message.success('更新角色成功！！');
      await this.initUserList();
      this.setRolesDialogVisible = false;

    },

  },

}
</script>

<style scoped>

  .searchBox{
    display: flex;
    margin-bottom: 10px;
  }
  .el-table{
    margin-bottom: 20px;
  }
</style>
